#include "http.h"
#include <QDebug>
#include <QEventLoop>
#include <QFile>
#include <QFileInfo>
#include <QHttpPart>


http::http(QString httpUrl, QObject *parent)
    : QObject{parent}
{
    setHttpUrl(httpUrl);
}

http::~http()
{

}

void http::setHttpUrl(QString url)
{
    this->m_httpUrl = url;
}

QString http::getHttpUrl()
{
    return this->m_httpUrl;
}

void http::setSuffix(QString suffix)
{
    this->m_suffix = suffix;
}

QString http::getSuffix()
{
    return this->m_suffix;
}

void http::requestFinish(QNetworkReply* reply)
{
    // 获取http状态码
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(statusCode.isValid())
        qDebug() << "status code=" << statusCode.toInt();

    QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    if(reason.isValid())
        qDebug() << "reason=" << reason.toString();

    QNetworkReply::NetworkError err = reply->error();
    if(err != QNetworkReply::NoError) {
        qDebug() << "Failed: " << reply->errorString();
    } else {
        emit requestFinished(reply->readAll());
        // 获取返回内容
        qDebug() << reply->readAll();
    }
}

void http::httpGetHandle(QString suffix)
{
    if(getHttpUrl().isNull()) return;
    QNetworkRequest request;
    QNetworkAccessManager manager;
    connect(&manager, &QNetworkAccessManager::finished, this, &http::requestFinish);

    request.setUrl(QUrl(getHttpUrl().append(suffix)));
    QNetworkReply* reply = manager.get(request);

    QEventLoop loop;
    connect(reply,&QNetworkReply::finished,&loop,&QEventLoop::quit);
    loop.exec();
}

void http::httpPostHandle(QByteArray data, QString suffix)
{
    if(getHttpUrl().isNull()) return;
    QNetworkRequest request;
    QNetworkAccessManager manager;
    connect(&manager, &QNetworkAccessManager::finished, this, &http::requestFinish);

    setSuffix(suffix);
    request.setUrl(QUrl(getHttpUrl().append(suffix)));    //要请求的网址

    //请求头设置
//    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply* reply = manager.post(request, data);        //post请求头+传输的数据

    //开启事件循环，直到请求完成
    QEventLoop loop;
    connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress1(qint64, qint64)));
    connect(reply,&QNetworkReply::finished,&loop,&QEventLoop::quit);
    loop.exec();
}

void http::uploadProgress1(qint64 sendBytes, qint64 allBytes)
{
    emit this->uploadProgressChanged(getSuffix(), sendBytes, allBytes);
//    qDebug() << sendBytes << allBytes;
}
